package m

import (
	"fmt"

	"github.com/globalsign/mgo/bson"
	log "github.com/sirupsen/logrus"

	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"
	"GameServer/Game/errors"
)

type Mail struct {
	BaseM
	Id      bson.ObjectId `bson:"_id" json:"id"`
	Type    int64         `bson:"type" json:"type"` // 0.自己邮件 1.系统邮件 2.好友赠送卡片邮件
	Title   string        `bson:"title" json:"title"`
	Content string        `bson:"content" json:"content"`
	Res     []*Goods      `bson:"res" json:"res"` // 邮件物品
	Time    int64         `bson:"time" json:"time"`
	Status  int64         `bson:"status" json:"status"` //1 已读  2 已经领取奖励  3 删除
}

type UserMail struct {
	BaseM
	Uid      bson.ObjectId    `bson:"_id" json:"uid"`
	Mails    map[string]*Mail `bson:"mails" json:"mails"`
	SysMails map[string]*Mail `bson:"sysMails" json:"sysMails"`
}

func NewUserMail() cache.EntryI {
	return &UserMail{Mails: make(map[string]*Mail, 0), SysMails: make(map[string]*Mail, 0)}
}

// 保存信息
func (uMail *UserMail) Save() (err error) {
	mdata := make(map[string]interface{}, 0)
	mdata["_id"] = uMail.Uid

	if uMail.Mails != nil && len(uMail.Mails) != 0 {
		mdata["mails"] = uMail.Mails
	}
	if uMail.SysMails != nil && len(uMail.SysMails) != 0 {
		mdata["sysMails"] = uMail.SysMails
	}
	err = dbmodule.MgoDB.GameDB.Upsert("userMail", bson.M{"_id": uMail.Uid}, mdata)
	if err != nil {
		return
	}
	return
}

func (uMail *UserMail) Load(key interface{}) (err error) {
	switch key.(type) {
	case string:
		if key.(string) == "" {
			return errors.New("无效的key load, key empty")
		}
		uMail.Uid = bson.ObjectIdHex(key.(string))
	case bson.ObjectId:
		uMail.Uid = key.(bson.ObjectId)
	default:
		log.WithFields(log.Fields{
			"method": "UserMail_Load",
			"data":   key,
		}).Error("无效的key load")
		return errors.New("无效的key load")
	}
	return uMail.LoadData()
}

// 加载数据
func (uMail *UserMail) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne("userMail", bson.M{"_id": uMail.Uid}, nil, &uMail)
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		return
	}
	if uMail.SysMails == nil {
		uMail.SysMails = make(map[string]*Mail, 0)
	}
	if uMail.Mails == nil {
		uMail.Mails = make(map[string]*Mail, 0)
	}
	return
}

// 更新数据

func (uMail *UserMail) Update(val *UserMail) {
	Cache.Put("userMail", uMail.Uid.Hex(), val)
	val.UpdateData()
}

// 获取邮件 信息
func (uMail *UserMail) GetMailByIds(ids []string) (r []*Mail) {
	mIds := make(map[string]string, 0)
	flag := false
	for _, id := range ids {
		if v, ok := uMail.Mails[id]; ok {
			r = append(r, v)
			continue
		}
		if v, ok := uMail.SysMails[id]; ok {
			r = append(r, v)
			continue
		}
		flag = true
		mIds[id] = id
	}

	if flag {
		sysMailList, err := GetAllSysMails()
		if err != nil {
			return
		}

		for _, item0 := range sysMailList {
			item := item0
			if _, ok := uMail.SysMails[item.Id.Hex()]; ok {
				continue
			}
			uMail.SysMails[item.Id.Hex()] = item
			if _, ok := mIds[item.Id.Hex()]; ok {
				r = append(r, item)
			}
		}
		uMail.Update(uMail)
	}
	return
}

// 阅读邮件
func (uMail *UserMail) ReadMails(ids []string) {
	for _, item := range uMail.GetMailByIds(ids) {
		if item.Status != 0 {
			continue
		}
		item.Status = 1
	}
}

// 邮件奖励
func (uMail *UserMail) RewardsMails(ids []string) {
	defer uMail.Update(uMail)
	for _, item := range uMail.GetMailByIds(ids) {
		if item.Status == 2 || item.Status == 3 || item.Res == nil || len(item.Res) == 0 {
			continue
		}
		item.Status = 2
	}
}

// 删除邮件
func (uMail *UserMail) DeleteMails(ids []string) {
	defer uMail.Update(uMail)
	for _, id := range ids {
		if v, ok := uMail.SysMails[id]; ok {
			fmt.Println("删除系统邮件：", id)
			v.Status = 3
			continue
		}
		delete(uMail.Mails, id)
	}
}

// 添加邮件
func (uMail *UserMail) AddMail(mail *Mail) (r *Mail) {
	defer uMail.Update(uMail)
	mail.Id = bson.NewObjectId()
	uMail.Mails[mail.Id.Hex()] = mail
	return mail
}

// 添加系统邮件
func (uMail *UserMail) AddSysMail(mail *Mail) {
	defer uMail.Update(uMail)
	uMail.SysMails[mail.Id.Hex()] = mail
}

func (u *User) GetUserMail() (r *UserMail) {
	v, _ := Cache.Get("userMail", u.Uid.Hex())
	r = v.(*UserMail)
	return
}

// 邮件列表
func (u *User) MailList() (r []*Mail, err error) {
	sysMailList, err := GetAllSysMails()
	if err != nil {
		return
	}
	v, _ := Cache.Get("userMail", u.Uid.Hex())
	uMail := v.(*UserMail)

	mList := make(map[string]bool, 0)

	for _, item := range sysMailList {
		// 系统邮件创建时间 小于 玩家注册时间 ，不用发此邮件
		if item.Time < u.RegisterTime {
			continue
		}
		mList[item.Id.Hex()] = true
		if v, ok := uMail.SysMails[item.Id.Hex()]; ok {
			if v.Status != 3 {
				r = append(r, v)
			}
			continue
		}
		r = append(r, item)
		uMail.SysMails[item.Id.Hex()] = item
	}
	// 删除已经删除的系统邮件列表
	for id, _ := range uMail.SysMails {
		if _, ok := mList[id]; ok {
			continue
		}
		delete(uMail.SysMails, id)
	}

	for _, item := range uMail.Mails {
		r = append(r, item)
	}

	uMail.Update(uMail)
	return
}

// 全服系统邮件
func GetAllSysMails() (list []*Mail, err error) {
	list = make([]*Mail, 0)
	err = dbmodule.MgoDB.GameDB.FindAll("sysMail", nil, nil, &list)
	if err != nil {
		return
	}
	return
}

// 添加系统邮件
func AddSysMails(mail *Mail) (err error) {
	err = dbmodule.MgoDB.GameDB.Upsert("sysMail", bson.M{"_id": mail.Id}, mail)
	if err != nil {
		return
	}
	return
}
